from pprint import pprint

from django.shortcuts import render, redirect, HttpResponse
from django.contrib.auth import authenticate, login, logout

from mytest import models
from mytest.utils.forms import *


# 登陆视图
def login_view(request):
    # context = {}
    #
    # if request.method == "POST":
    #     username = request.POST['username']
    #     password = request.POST['password']
    #     user = authenticate(request, username=username, password=password)
    #     if user is not None:
    #         login(request, user)
    #         return redirect('mytest:workbench')
    #     else:
    #         context['error_message'] = "用户名或密码错误"
    # return render(request, "mytest/login.html",  context)

    if request.method == "get":
        form = LoginModelForm()
        return render(request, "mytest/login.html", {"form": form})

    form = LoginModelForm(data=request.POST)
    if form.is_valid():
        # 验证成功，获取到的用户名和密码
        # {'username': '123', 'password': '123'}
        # {'username': '123', 'password': '3f0dadd26303941f016090c7505ac486'}
        print(form.cleaned_data)

        # 去数据库校验用户名和密码是否正确
        admin_object = models.Admin.objects.filter(**form.cleaned_data).first()

        # 在数据库中没找到用户，返回登陆界面，并报错提示。
        if not admin_object:
            form.add_error("password", "用户名或密码错误")  # 添加报错提示
            return render(request, "mytest/login.html", {"form": form})

        # 用户名和密码正确
        # 网络生成随机字符串，写到用户浏览器的cookie中：再写到session中：
        request.session["info"] = {"id": admin_object.id, "name": admin_object.username}
        # print(request.session["info"])
        return redirect("/mytest/chart/")

    return render(request, "mytest/login.html", {"form": form})


# 退出登陆视图
def logout_view(request):
    # logout(request)
    # 清除当前用户的session
    request.session.clear()
    return redirect("mytest:login")


# 主界面视图
def workbench(request):
    # 去数据库中获取所有的部门列表
    queryset = models.Department.objects.all()

    # form = EmpForm()
    # if form.is_valid():
    return render(
        request,
        "mytest/workbench.html",
        {
            "queryset": queryset
        }
    )
    # return HttpResponse("这是GET请求")
